<?php

class RequestRestResource extends RestResource {

    private static $instance;
    protected $rootResourcePath = '/users';

    protected function __construct() {
        parent::__construct('Request', '/requests');
    }

    /**
     * @return RequestRestResource
     */
    public static function singleton() {
        if (!isset(self::$instance)) {
            self::$instance = new RequestRestResource();
        }
        return self::$instance;
    }

    public function findByUserId($userId, $id) {
        $b = YougoRestClient::singleton()->get($this->rootResourcePath . '/' . $userId . $this->resourcePath . '/' . $id);
        return $this->jsonToObject($b->getResponseText());
    }

    public function findAllByUserId($userId) {
        $b = YougoRestClient::singleton()->get($this->rootResourcePath . '/' . $userId . $this->resourcePath);
        return $this->jsonToObjectList($b->getResponseText());
    }

    public function createByUserId($userId, $resource) {
        $b = YougoRestClient::singleton()->post($this->rootResourcePath . '/' . $userId . $this->resourcePath, $this->objectToJson($resource));

        // Extracts id from location
        $location = $b->getResponseHeader('Location');
        $id = preg_replace('/.*\/(\d+)/', '\\1', $location);
        return $id;
    }

    public function updateByUserId($userId, $resource) {
        $b = YougoRestClient::singleton()->put($this->rootResourcePath . '/' . $userId . $this->resourcePath . '/' . $resource['id'], $this->objectToJson($resource));
    }

    public function deleteByUserId($userId, $id) {
        $b = YougoRestClient::singleton()->delete($this->rootResourcePath . '/' . $userId . $this->resourcePath . '/' . $id);
    }

    public function searchByUserId($userId, $from, $to, $requestStatus = array()) {
        $parameters = array(
            'from' => $from->format('m/d/Y'),
            'to' => $to->format('m/d/Y'),
            'requestStatus' => $requestStatus
        );
        $b = YougoRestClient::singleton()->get($this->rootResourcePath . '/' . $userId . $this->resourcePath, $parameters);
        return $this->jsonToObjectList($b->getResponseText());
    }

    protected function jsonToObject($json) {
        $resourceArray = json_decode($json);
        $resource = new $this->resourceClass;
        foreach ($resourceArray as $key => $value) {
            $resource->set($key, $value);
        }
        return $resource;
    }

    protected function jsonToObjectList($json) {
        $resourcesArray = json_decode($json);
        $resources = array();
        foreach ($resourcesArray as $resourceArray) {
            $resource = new $this->resourceClass;
            foreach ($resourceArray as $key => $value) {
                $resource->set($key, $value);
            }
            $resources[] = $resource;
        }
        return $resources;
    }

}